import request from '@/utiles/request.js'

// 用户登录
export const loginService = async (loginData) => {
  return await request.post('/api/user/login', loginData)
}

export const logcallback = async (logData)=> {
  return await  request.post('/opera/insert',logData)
}


// 获取工作列表
export const getWorkListService = async (params = {}) => {
  return await request.get('/work/list', { params })
}
// 处理工作项（通过/驳回）
export const handleWorkItemService = async (workId, action, comment = '', extraData = {}) => {
  // 将前端的action转换为后端期望的status值
  const status = action === 'approve' ? 3 : 1  // 3=通过, 1=驳回

  console.log(`调用API更新工作项: ID=${workId}, Action=${action}, Status=${status}, Comment=${comment}, ExtraData=`, extraData)

  try {
    // 使用表单数据格式发送，匹配后端的@RequestParam
    const formData = new FormData()
    formData.append('id', workId.toString())
    formData.append('status', status.toString())
    if (comment) {
      formData.append('comment', comment)
    }
    // 添加额外的员工信息字段
    if (extraData.dep) {
      formData.append('dep', extraData.dep)
    }
    if (extraData.staff) {
      formData.append('staff', extraData.staff)
    }
    if (extraData.staffid) {
      formData.append('staffid', extraData.staffid)
    }
    if (extraData.dir) {
      formData.append('dir', extraData.dir)
    }

    return await request.put('/work/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  } catch (error) {
    console.error('API调用失败:', error)

    // 如果仍然失败，尝试使用JSON格式
    try {
      const requestData = {
        id: workId,
        status: status
      }
      if (comment) {
        requestData.comment = comment
      }
      // 添加额外的员工信息字段
      if (extraData.dep) {
        requestData.dep = extraData.dep
      }
      if (extraData.staff) {
        requestData.staff = extraData.staff
      }
      if (extraData.staffno) {
        requestData.staffno = extraData.staffno
      }
      if (extraData.dir) {
        requestData.dir = extraData.dir
      }

      return await request.put('/work/update', requestData)
    } catch (jsonError) {
      console.error('JSON格式调用也失败:', jsonError)
      throw jsonError
    }
  }
}

// 用户信息获取服务
export const userGetInfoService = async () => {
  return await request.get('/api/review/user/info')
}

// 修改密码服务
export const changePasswordService = async (passwordData) => {
  return await request.post('/api/user/change-password', passwordData)
}

// 退出登录服务
export const logoutService = async () => {
  return await request.post('/api/review/user/logout')
}
